// 预加载工具函数
export class PreloadManager {
  private static instance: PreloadManager
  private cache = new Map<string, any>()

  static getInstance(): PreloadManager {
    if (!PreloadManager.instance) {
      PreloadManager.instance = new PreloadManager()
    }
    return PreloadManager.instance
  }

  // 预加载图片
  async preloadImage(url: string): Promise<HTMLImageElement> {
    if (this.cache.has(url)) {
      return this.cache.get(url)
    }

    return new Promise((resolve, reject) => {
      const img = new Image()
      img.onload = () => {
        this.cache.set(url, img)
        resolve(img)
      }
      img.onerror = reject
      img.src = url
    })
  }

  // 预加载音频
  async preloadAudio(url: string): Promise<HTMLAudioElement> {
    if (this.cache.has(url)) {
      return this.cache.get(url)
    }

    return new Promise((resolve, reject) => {
      const audio = new Audio()
      audio.oncanplaythrough = () => {
        this.cache.set(url, audio)
        resolve(audio)
      }
      audio.onerror = reject
      audio.src = url
    })
  }

  // 清理缓存
  clearCache() {
    this.cache.clear()
  }
}

// 导出单例
export const preloadManager = PreloadManager.getInstance()
